package com.rzn.reading.service.impl;

import com.rzn.reading.BeanMapper;
import com.rzn.reading.BusinessException;
import com.rzn.reading.entity.Note;
import com.rzn.reading.mapper.NoteMapper;
import com.rzn.reading.model.dto.note.*;
import com.rzn.reading.service.NoteService;
import com.rzn.reading.utils.StringDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 笔记表 服务实现类
 * </p>
 *
 * @author rzn
 * @since 2022-02-12
 */
@Service
public class NoteServiceImpl implements NoteService {
    @Autowired
    private NoteMapper noteMapper;

    @Override
    public Boolean createNote(NoteCreateInputDTO noteCreateInputDTO) {
        Note note = BeanMapper.map(noteCreateInputDTO, Note.class);
        return noteMapper.insert(note) == 1;
    }

    @Override
    public NoteDetailDTO getNoteDetail(Integer id) {
        return noteMapper.getNoteDetail(id);
    }

    @Override
    public Boolean updateNote(NoteUpdateDTO noteUpdateDTO) {
        Note note = BeanMapper.map(noteUpdateDTO, Note.class);
        return noteMapper.updateByPrimaryKey(note) == 1;
    }

    @Override
    public Map<String, Object> getNoteItemList(QueryNoteDTO queryNoteDTO) {
        QueryNotePageParam notePageParam = BeanMapper.map(queryNoteDTO, QueryNotePageParam.class);
        if (queryNoteDTO.getPage() != null && queryNoteDTO.getPageSize() != null) {
            notePageParam.setOffset((queryNoteDTO.getPage() - 1) * queryNoteDTO.getPageSize());
        }
        queryNoteDTO.setState(1);
        List<NoteDetailDTO> res = noteMapper.selectItemByPage(notePageParam);
        notePageParam.setOffset(null);
        notePageParam.setPageSize(null);
        List<NoteDetailDTO> allItem = noteMapper.selectItemByPage(notePageParam);
        int size = allItem.size();
        Map<String, Object> map = new HashMap<>();
        map.put("row", res);
        map.put("size", size);
        return map;
    }

    @Override
    public Boolean updateNoteState(Integer id, Integer state) {
        return noteMapper.updateNoteStage(id, state) == 1;
    }

    @Override
    public Boolean deleteNote(Integer id, Integer userId) {
        Note note = noteMapper.selectByPrimaryKey(id);
        if (note.getUserId() != userId) {
            throw new BusinessException("你不是改笔记的创建者，无法删除");
        }
        return noteMapper.deleteByPrimaryKey(id) == 1;
    }
}
